﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BCGC.BLL.Helper;
using System.Collections.Generic;
using BCGC.BLL.BusinessObject;
using Jalal.Library.DataStructure;
using Jalal.Library.Utility;
using Jalal.Library.Web.Control;
using log4net;

public partial class Admin_Contact_Default : AdminBasePage
{
    private int CurrentPageIndex
    {
        get
        {
            if (ViewState["CurrentPageIndex"] == null)
                ViewState["CurrentPageIndex"] = 1;
            return (int)ViewState["CurrentPageIndex"];
        }
        set { ViewState["CurrentPageIndex"] = value; }
    }

    private string SortOrder
    {
        get
        {
            if (ViewState["SortOrder"] == null)
                ViewState["SortOrder"] = "ContactDateTime Desc";
            return (string)ViewState["SortOrder"];
        }
        set { ViewState["SortOrder"] = value; }
    }

    private int TotalData
    {
        get
        {
            if (ViewState["TotalData"] == null)
                ViewState["TotalData"] = 0;
            return (int)ViewState["TotalData"];
        }
        set { ViewState["TotalData"] = value; }
    }

    private void BindPager()
    {
        List<string> pages = new List<string>();
        int pageCount = (TotalData / grvContacts.PageSize) + ((TotalData % grvContacts.PageSize) > 0 ? 1 : 0);
        for (int i = 1; i <= pageCount; i++)
            pages.Add(i.ToString());

        rptPager.DataSource = pages;
        rptPager.DataBind();
    }

    protected void Page_Change(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "PagingCommand")
        {
            CurrentPageIndex = Convert.ToInt32(e.CommandArgument);
            BindGrid();
            BindPager();
        }
    }

    protected void Grid_Sort(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "Sort")
        {
            grvContacts.EditIndex = -1;
            SortOrder = (string)e.CommandArgument;
            BindGrid();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
            BindPager();
        }
    }

    private void BindGrid()
    {
        try
        {
            bool? isRead;
            if (ddlUnread.SelectedValue == "-1")
                isRead = null;
            else
                isRead = Security.BindBooleanInput(ddlUnread.SelectedValue, SecurityLevel.Three);

            int totalData = 0;
            ReadWriteCustomCollection<Contact> contact = Contact.GetAllContact(CurrentPageIndex, SortOrder, grvContacts.PageSize,
                string.IsNullOrEmpty(tbxName.Text) ? null : Security.BindStringInput(tbxName.Text, SecurityLevel.Three),
                string.IsNullOrEmpty(tbxOrganization.Text) ? null : Security.BindStringInput(tbxOrganization.Text, SecurityLevel.Three),
                contactDateFrom.Date, contactDateTo.Date, isRead, out totalData);

            TotalData = totalData;

            grvContacts.DataSource = contact;
            grvContacts.DataBind();
        }
        catch (Exception ex)
        {
            // Write the log into handled exception list
            ILog log = LogHelper.GetHandledFileLogger("Contacts");
            if (log.IsErrorEnabled)
                log.Error("Failed to load admin contact list", ex);
        }
    }

    protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            CheckBox cbxSelectAll = (CheckBox)e.Row.FindControl("cbxSelectAll");
            cbxSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + grvContacts.ClientID
                + "','" + cbxSelectAll.ClientID + "','cbxSelect')");
        }
        else if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal ||
            e.Row.RowState == DataControlRowState.Alternate))
        {
            Contact contact = (Contact)e.Row.DataItem;

            HyperLink hlkContactSubject = (HyperLink)e.Row.FindControl("hlkContactSubject");
            if (hlkContactSubject != null && contact != null)
            {
                hlkContactSubject.NavigateUrl = CustomSiteMap.ReadMessage + "?id=" + contact.ContactId.ToString();
            }

            HyperLink hlkReadMessage = (HyperLink)e.Row.FindControl("hlkReadMessage");
            if (hlkReadMessage != null && contact != null)
            {
                hlkReadMessage.NavigateUrl = CustomSiteMap.ReadMessage + "?id=" + contact.ContactId.ToString();
            }

            ThemeImage imgRead = (ThemeImage)e.Row.FindControl("imgRead");
            if (imgRead != null && contact != null)
            {
                imgRead.ImageUrl = (contact.IsRead ? "mail_read.gif" : "mail_unread.gif");
            }
        }
    }

    protected void Pager_DataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (Convert.ToInt32(e.Item.DataItem) == CurrentPageIndex)
            {
                LinkButton lkbPageIndex = (LinkButton)e.Item.FindControl("lkbPageIndex");
                lkbPageIndex.CssClass = "page-index-selected";
            }
        }
    }

    protected void Update_Command(object sender, CommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "Update" && Page.IsValid)
            {
                List<int> contactItemIds = new List<int>();

                foreach (GridViewRow row in grvContacts.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        CheckBox cbxSelect = (CheckBox)row.FindControl("cbxSelect");
                        if (cbxSelect != null && cbxSelect.Checked)
                        {
                            Label lblId = (Label)row.FindControl("lblId");
                            contactItemIds.Add(Convert.ToInt32(lblId.Text));
                        }
                    }
                }

                if (e.CommandArgument.ToString() == "Top")
                {
                    if (ddlActionType.SelectedValue == "Delete")
                    {
                        // Write the log into admin log list
                        ILog log = LogHelper.GetAdminActionLogger("Contacts");
                        if (log.IsErrorEnabled)
                            log.Error("Admin deleted some contacts", new Exception("Deleted: " + contactItemIds.Count + " contacts"));

                        Contact.Delete(contactItemIds);
                        uccResponse.SetSuccessMessage("Items Deleted");
                    }
                    else if (ddlActionType.SelectedValue == "Read")
                    {
                        Contact.UpdateRead(contactItemIds);
                        uccResponse.SetSuccessMessage("Items Marked As Read");
                    }
                    else if (ddlActionType.SelectedValue == "Unread")
                    {
                        Contact.UpdateUnread(contactItemIds);
                        uccResponse.SetSuccessMessage("Items Marked As Unread");
                    }
                }
                else if (e.CommandArgument.ToString() == "Bottom")
                {
                    if (ddlActionType2.SelectedValue == "Delete")
                    {
                        // Write the log into admin log list
                        ILog log = LogHelper.GetAdminActionLogger("Contacts");
                        if (log.IsErrorEnabled)
                            log.Error("Admin deleted some contacts", new Exception("Deleted: " + contactItemIds.Count + " contacts"));

                        Contact.Delete(contactItemIds);
                        uccResponse.SetSuccessMessage("Items Deleted");
                    }
                    else if (ddlActionType2.SelectedValue == "Read")
                    {
                        Contact.UpdateRead(contactItemIds);
                        uccResponse.SetSuccessMessage("Items Marked As Read");
                    }
                    else if (ddlActionType2.SelectedValue == "Unread")
                    {
                        Contact.UpdateUnread(contactItemIds);
                        uccResponse.SetSuccessMessage("Items Marked As Unread");
                    }
                }

                BindGrid();
                BindPager();
            }
        }
        catch (Exception ex)
        {
            // Write the log into handled exception list
            ILog log = LogHelper.GetHandledFileLogger("Contacts");
            if (log.IsErrorEnabled)
                log.Error("Failed to update admin contact list", ex);
        }
    }

    protected void Search_Click(object sender, EventArgs e)
    {
        BindGrid();
        BindPager();
    }
}
